import store from '@/store'
import { getSceneCouponDetailByIds, useSceneCoupon } from '@/api/coupon'
import { getBackEndConfig, getUserActivity } from '@/api/common'
import { invokeAPi } from '@/xz-fn.js'
import DiyDialog from '@/components/diy-dialog'
import { isPassVersionByApp } from '@/utils/judge'
import { gotoMember } from '@/utils'
class SceneMg {
  constructor (cfgName = 'cjqhms') {
    this.cfgName = cfgName
    this.cfgData = []
    isPassVersionByApp({
      '22': { v: '3.3.4.0' },
      '111': { v: '3.2.10.0' }
    }) && this.getConfigData()
      .then(data => {
        this.cfgData = data
      })
  }
  /** 获取场景券配置数据 */
  async getConfigData () {
    const rs = await getBackEndConfig({
      app_id: store.getters.appInfo.appID,
      version: store.getters.appInfo.version,
      union_id: store.getters.appInfo.channel,
      keyname: this.cfgName
    }).catch(() => null)
    const { params } = rs?.data || {}
    if (Array.isArray(params)) {
      return params
    }
    return []
  }
  /** 获取优惠券or秒杀活动详情 */
  async getDetail ({ seckill_id, type }) {
    if (type === 'coupon') {
      const seckill_ids = String(seckill_id).split(',')
      return getSceneCouponDetailByIds(seckill_ids).then(res => res).catch(() => null)
    }
    return this.getActivityDetail(seckill_id)
  }
  /** 获取秒杀活动详情 */
  async getActivityDetail (act_id) {
    const rs = await getUserActivity({ act_id }).catch(() => null)
    const data = rs?.data?.data
    if (data && data.sub_code === 'not_join' && data.act_info) {
      return { ...data.act_info }
    }
    return null
  }
  /** 检查是否符合条件 */
  async detectSeckilScence (sceneName) {
    // 未联网
    if (!window.navigator.onLine) return false

    // 用户未登录
    if (!store.getters.hasLogin) return false

    // 查询指定场景数据
    const sceneItem = this.cfgData.filter(v => v.scene.includes(sceneName))?.[0]
    if (!sceneItem?.list?.length) return false
    // 判断是否已展示过
    const handleInfo = this.getStorageClose(sceneName, sceneItem.interval_reset)
    if (handleInfo.showLastTime) return false
    // 判断弹出总数
    const count = ++handleInfo.count
    // const total = localStorage.getItem('_scene_coupon_seckill_total_' + targetSeckil.seckill_id) || 0
    // localStorage.setItem('_scene_coupon_seckill_total_' + targetSeckil.seckill_id, total + 1)

    // 点击触发大于预定值--避免累计点击数过大
    const maxCount = Math.max(...sceneItem.list.map(({ count }) => count))
    if (maxCount < count) return false

    // 记录点击次数
    handleInfo.triggerLastTime = Date.now()
    this.setStorageClose(handleInfo, sceneName)
    // 找出匹配次数且非购买过终身的数据，查询相关详情数据
    const detailPs = sceneItem.list.filter(({ count: a, pkg_id, type }) => {
      if (count !== a) return false
      // eslint-disable-next-line eqeqeq
      if (type === 'seckill' && store.getters.userInfo.buy_right_package?.some(({ pkg_id: id, unlimited }) => id == pkg_id && unlimited)) return false
      return true
    }).map(async item => {
      try {
        item.detail = await this.getDetail(item)
      } catch (error) {}
    })

    await Promise.all(detailPs)

    // 判断是否有满足条件
    const targetSeckil = sceneItem.list.find(({ count: a, detail }) => detail && count === a)
    if (!targetSeckil) return false

    // 展示
    handleInfo.showLastTime = Date.now()
    // 记录最后展示事件
    this.setStorageClose(handleInfo, sceneName)
    this.show(targetSeckil)
    return true
  }
  getStorageClose (sceneName, interval_reset) {
    if (!sceneName) return console.error('sceneName is a required field, but it is empty')
    const val = localStorage.getItem(`_scene_coupon_seckill_${sceneName}_`)
    let data
    try {
      data = JSON.parse(val)
    } catch (e) {
    }
    // 超过间隔小时，重置次数
    if (
      !data ||
      !interval_reset ||
      Date.now() - data.triggerLastTime > interval_reset * 60 * 60 * 1000
    ) {
      return {
        count: 0, // 触发次数
        triggerLastTime: 0, // 最后触发时间（操作行为）
        showLastTime: 0 // 最后展示时间（弹出场景券or秒杀）
      }
    }
    return data
  }
  setStorageClose (data, sceneName) {
    if (!sceneName) return console.error('sceneName is a required field, but it is empty')
    const storageName = `_scene_coupon_seckill_${sceneName}_`
    localStorage.setItem(storageName, JSON.stringify(data))
  }
  /** 显示场景券or秒杀 */
  async show (info) {
    const { exhibit_id, type, seckill_id } = info
    invokeAPi('xz_substat_action', exhibit_id)
    if (type === 'coupon') {
      DiyDialog('sceneCouponDialog', {
        dialogVisible: true,
        info: info
      }).then(async () => {
        // 唤起优惠券领取
        const seckill_ids = String(seckill_id).split(',').map(id => Number(id))
        await useSceneCoupon({
          coupon_id: seckill_ids
        })
        gotoMember()
      })
    } else {
      // 唤起秒杀活动
      info.toWinId = 'XZDesktopFlashSale'
      // encodeURIComponent解决跨端时客户端对字符串中的“/”截断问题
      invokeAPi('OpenUserCenterFlashSale', encodeURIComponent(JSON.stringify(info)))
    }
  }
}

const sceneMg = new SceneMg()
export default sceneMg
